import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject

from src.ui.radio_list import RadioList
from src.ui.status_bar import StatusBar

class MainWindow(Gtk.Window):
    def __init__(self, app):
        super().__init__(title="GDRadio")
        self.app = app
        self.set_default_size(800, 600)
        
        # Main layout
        self.main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(self.main_box)
        
        # Header bar
        self._setup_header_bar()
        
        # Content area
        self.content_paned = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
        self.main_box.pack_start(self.content_paned, True, True, 0)
        
        # Radio list
        self.radio_list = RadioList(self.app)
        self.content_paned.pack1(self.radio_list, True, False)
        
        # Details view
        self.details_view = Gtk.Box()
        self.content_paned.pack2(self.details_view, True, False)
        
        # Status bar
        self.status_bar = StatusBar()
        self.main_box.pack_end(self.status_bar, False, False, 0)
        
        # Connect signals
        self.connect("delete-event", self._on_delete)
    
    def _setup_header_bar(self):
        header = Gtk.HeaderBar()
        header.set_show_close_button(True)
        self.set_titlebar(header)
        
        # Play controls
        self.play_btn = Gtk.Button.new_from_icon_name("media-playback-start", Gtk.IconSize.BUTTON)
        self.play_btn.connect("clicked", self._on_play_clicked)
        header.pack_start(self.play_btn)
        
        # Volume control
        self.volume_btn = Gtk.VolumeButton()
        self.volume_btn.set_value(self.app.player.volume)
        self.volume_btn.connect("value-changed", self._on_volume_changed)
        header.pack_end(self.volume_btn)
    
    def _on_play_clicked(self, button):
        if self.app.player.is_playing():
            self.app.player.pause()
            button.set_image(Gtk.Image.new_from_icon_name(
                "media-playback-start", Gtk.IconSize.BUTTON))
        else:
            selected = self.radio_list.get_selected_station()
            if selected:
                self.app.player.play(selected)
                button.set_image(Gtk.Image.new_from_icon_name(
                    "media-playback-pause", Gtk.IconSize.BUTTON))
    
    def _on_volume_changed(self, button, value):
        self.app.player.volume = value
    
    def _on_delete(self, window, event):
        self.app.config.set("window_size", [window.get_size().width, window.get_size().height])
        Gtk.main_quit()